package com.ficus.road.maintain.client;

import com.fasterxml.jackson.databind.JsonNode;
import com.ficus.road.maintain.core.model.GpsHistory;
import com.google.common.collect.Lists;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.Objects;

@Component
@RequiredArgsConstructor
@Slf4j
public class GpsFixClient {
    private final RestTemplate restTemplate;

    public List<FixGpsLocation> fix(GpsHistory pre, GpsHistory post) {
        String url = "http://172.16.101.150:8081/api/route/road_graph?origin=" + pre.getLatitude() + "," + pre.getLongitude() +
                "&destination=" + post.getLatitude() + "," + post.getLongitude();
        JsonNode forObject = restTemplate.getForObject(url, JsonNode.class);
        if (Objects.isNull(forObject)){
            return Lists.newArrayList();
        }

        List<FixGpsLocation> result = Lists.newArrayList();
        JsonNode jsonNode = forObject.get("result");
        if (Objects.nonNull(jsonNode) && jsonNode.isArray()){
            for (JsonNode locationNode : jsonNode) {
                result.add(FixGpsLocation.builder().lat(locationNode.get("lat").asDouble()).lng(locationNode.get("lng").asDouble()).build());
            }
        }
        return result;
    }
}
